class Movie < ActiveRecord::Base
  validates_presence_of :title, :description, :message => "is needed!"
  validates_length_of :description, :minimum => 10, :too_short => "is too short!"
  validates_uniqueness_of :title, :message => "corresponds to an existing movie!"
  validates_inclusion_of :rating, :in => %w[G PG PG-13 R NC-17], :message => "is not a valid rating!"
  
  has_many :reviews, :dependent => :destroy
  
  def to_param
    "#{id}-#{title.gsub(/[^a-z0-9]+/i, '-').downcase}"
  end
  
  # Returns a formatted version of the date:
  def release_date
    unless self.released_on.blank?
      return self.released_on.strftime('%B %d, %Y')
    else
      return nil
    end
  end
  
  def self.required_age_for
    return {
      "G"     =>  0,
      "PG"    =>  0,
      "PG-13" =>  13,
      "R"     =>  17,
      "NC-17" =>  17
    }
  end
  
  def appropriate_for_birthdate?(birthdate)
    required_birthdate = Movie.required_age_for[self.rating].years.ago
    return required_birthdate > birthdate
  end
  
  def self.find_all_appropriate_for_birthdate(birthdate)
    @movies = Movie.find(:all)
    return @movies.select do |movie|
      movie.appropriate_for_birthdate?(birthdate)
    end
  end
  
  def average_score
    reviews = self.reviews
    if reviews.blank?
      return 0
    else
      cumulative = 0
      reviews.each do |review|
        cumulative += review.score
      end
      return cumulative/reviews.size
    end
  end
  
end
